package com.haoyun.mirage.auth.controller;

import com.google.common.collect.Sets;
import com.haoyun.common.constant.CommonConstant;
import com.haoyun.common.core.Result;
import com.haoyun.mirage.auth.vo.RoleVO;
import com.haoyun.mirage.auth.vo.UserVO;
import com.xiaoleilu.hutool.bean.BeanUtil;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * Created by twg on 2018/6/7.
 */
@RestController
public class AuthorizationController {
    /**
     * 获取认证后的用户信息
     *
     * @param authentication
     * @return
     */
    @GetMapping("authorization/user")
    public Result<UserVO> getUser(OAuth2Authentication authentication) {
        if (authentication == null || authentication.getUserAuthentication() == null) {
            throw new AccountExpiredException("用户已过期请重新登录！");
        }

        Map userMap = BeanUtil.beanToMap(authentication.getUserAuthentication().getPrincipal());
        UserVO user = new UserVO();
        user.setUserName((String) userMap.getOrDefault("username", ""));
        user.setRealName((String) userMap.getOrDefault("realName", ""));
        user.setCompId((Long) userMap.get("compId"));
        user.setUserLevel((Integer) userMap.get("userLevel"));
        user.setId((Long) userMap.get("id"));

        RoleVO role = null;
        Set<RoleVO> roles = Sets.newHashSet();
        Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) userMap.get("authorities");
        for (GrantedAuthority authority : authorities) {
            role = new RoleVO();
            role.setRoleCode(authority.getAuthority());
            roles.add(role);
        }
        user.setRolesSet(roles);
        return Result.buildSuccessResult(user);
    }
}
